#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "semaphore.h"

/*
 * 运行时会在当前文件创建FIFO
 * 共享文件夹不能创建FIFO，所以不能在共享文件夹运行
 */

typedef int (*process)(void *arg);

pid_t create_process(process entry, void *arg)
{
	int exit_value;
	pid_t pid;
	
	if(!entry)
		return -1;
	
	//创建子进程
	pid = fork();
	if(pid == 0)
	{
		//fork在子进程中返回0
		exit_value = entry(arg);
		exit(exit_value);
	}
	//fork在父进程中返回子进程的ID
	return pid;
}

int wait_process(void *arg)
{
	int id;
	
	//创建或打开信号量
	id = semaphore_create("/", 0);
	if(id == -1)
	{
		perror("semaphore_create");
		return -1;
	}
	
	//设置信号量的值为0
	if(semaphore_set_value(id, 0) == -1)
	{
		perror("semaphore_set_value");
		return -1;
	}
	
	while(1)
	{
		//等待信号量
		if(semaphore_wait(id) == -1)
			printf("wait semaphore failed\n");
		else
			printf("wait semaphore succeed\r\n");
	}
	return 0;
}

int write_process(void *arg)
{
	int id;
	
	//创建或打开信号量
	id = semaphore_create("/", 0);
	if(id == -1)
	{
		perror("semaphore_create");
		return -1;
	}
	
	while(1)
	{
		//释放信号量
		if(semaphore_post(id) == -1)
			printf("post semaphore failed\n");
		else
			printf("post semaphore succeed\r\n");
		sleep(1);
	}	
	return 0;
}

int main(int argv, char *argc[])
{
	pid_t pid1,pid2;
	
	//同时创建的进程其执行的先后顺序不确定
	pid1 = create_process(wait_process, "wait_process;");
	printf("wait_process PID=%d\r\n", pid1);
	
	pid2 = create_process(write_process, "write_process;");
	printf("write_process PID=%d\r\n", pid2);
	
	while(1)
	{
		sleep(10);
	}
}
